<!DOCTYPE HTML>
<html lang="zh-CN">




<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JavaNote_Spring_Day04, 深度学习 故障诊断 Java">
    <meta name="description" content="河海大学 | 计算机与信息学院 | 信号与信息处理">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>JavaNote_Spring_Day04 | 世庆的博客</title>
    <link rel="icon" type="image/png" href="/shiqing/favicon.png">

    <link rel="stylesheet" type="text/css" href="/shiqing/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/my.css">

    <script src="/shiqing/libs/jquery/jquery.min.js"></script>

    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 6.3.0"></head>




    <body>
        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/shiqing/" class="waves-effect waves-light">
                    
                    <img src="/shiqing/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">世庆的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/shiqing/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">世庆的博客</div>
        <div class="logo-desc">
            
            河海大学 | 计算机与信息学院 | 信号与信息处理
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/sqtian-hhu/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/sqtian-hhu/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/shiqing/medias/featureimages/17.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JavaNote_Spring_Day04</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/shiqing/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/shiqing/tags/Java%E6%A1%86%E6%9E%B6/">
                                <span class="chip bg-color">Java框架</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/shiqing/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-06-29
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/shiqing/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="day4"><a href="#day4" class="headerlink" title="day4"></a>day4</h2><p>spring中的JDBCTemlate以及Spring事务控制</p>
<ol>
<li>spring中的JdbcTemplate<br> JdbcTemplate的作用：<br>     他就是用于和数据库交互的，实现对表的CRUD操作<br> 如何创建该对象：<br> 对象中的常用方法</li>
</ol>
<span id="more"></span>	
<p>导入依赖坐标<br><?xml version="1.0" encoding="UTF-8"?><br><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><br>    <modelVersion>4.0.0</modelVersion></p>
<pre><code>&lt;groupId&gt;org.example&lt;/groupId&gt;
&lt;artifactId&gt;com.sqtian.springDay04_JdbcTemplate&lt;/artifactId&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;packaging&gt;jar&lt;/packaging&gt;


&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
        &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
        &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
        &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
        &lt;version&gt;5.1.6&lt;/version&gt;
    &lt;/dependency&gt;

&lt;/dependencies&gt;
</code></pre>
</project>
--------------------------------------------------------------------------------

<p>package com.sqtian.jdbctemplate;</p>
<p>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.datasource.DriverManagerDataSource;</p>
<p>&#x2F;**</p>
<ul>
<li>JdbcTemplate的最基本用法<br> *&#x2F;<br>public class JdbcTemplateDemo1 {<br> public static void main(String[] args) {<br> &#x2F;&#x2F;准备数据源,spring的内置数据源<br> DriverManagerDataSource ds &#x3D; new DriverManagerDataSource();<br> ds.setDriverClassName(“com.mysql.jdbc.Driver”);<br> ds.setUrl(“jdbc:mysql:&#x2F;&#x2F;localhost:3306&#x2F;lovelycc?characterEncoding&#x3D;utf8”);<br> ds.setUsername(“root”);<br> ds.setPassword(“root”);<br><br> &#x2F;&#x2F;1. 创建JdbcTemplate对象<br> JdbcTemplate jdbcTemplate &#x3D; new JdbcTemplate();<br> &#x2F;&#x2F;给jt设置数据源<br> jdbcTemplate.setDataSource(ds);<br> &#x2F;&#x2F;2. 执行操作<br> jdbcTemplate.execute(“insert into account(name,balance,uid)values(‘陆游’,1000,30)”);<br> }</li>
</ul>
<h2 id=""><a href="#" class="headerlink" title="}"></a>}</h2><p>其中含有new和大量set方法<br>可以通过spring的ioc进行配置</p>
<pre><code>配置bean.xml
</code></pre>
<?xml version="1.0" encoding="UTF-8"?>
<p><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd"></p>
<pre><code>&lt;!--配置jdbcTemplate--&gt;
&lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
    &lt;!-- collaborators and configuration for this bean go here --&gt;
    &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;

&lt;/bean&gt;


&lt;bean id=&quot;dataSource&quot; class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
    &lt;!-- collaborators and configuration for this bean go here --&gt;
    &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/lovelycc?characterEncoding=utf8&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;username&quot; value=&quot;root&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;password&quot; value=&quot;root&quot;&gt;&lt;/property&gt;

&lt;/bean&gt;

&lt;!-- more bean definitions go here --&gt;
</code></pre>
</beans>

<hr>
<p>package com.sqtian.jdbctemplate;</p>
<p>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;<br>import org.springframework.jdbc.core.JdbcTemplate;</p>
<p>&#x2F;**</p>
<ul>
<li>JdbcTemplate的最基本用法<br> *&#x2F;<br>public class JdbcTemplateDemo2 {<br> public static void main(String[] args) {<br> &#x2F;&#x2F;1. 获取容器<br> ApplicationContext ac &#x3D; new ClassPathXmlApplicationContext(“bean.xml”);<br> &#x2F;&#x2F;2. 获取对象<br> JdbcTemplate jt &#x3D; ac.getBean(“jdbcTemplate”,JdbcTemplate.class);<br> &#x2F;&#x2F;3. 执行操作<br> jt.execute(“insert into account(name,balance,uid)values(‘凌雪’,2000,31)”);<br> }</li>
</ul>
<p>}</p>
<hr>
<p>增删改查</p>
<p>package com.sqtian.jdbctemplate;</p>
<p>import com.sqtian.domain.Account;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;<br>import org.springframework.jdbc.core.BeanPropertyRowMapper;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.RowMapper;</p>
<p>import java.sql.ResultSet;<br>import java.sql.SQLException;<br>import java.util.List;</p>
<p>&#x2F;**</p>
<ul>
<li><p>JdbcTemplate的CRUD操作<br> *&#x2F;<br>public class JdbcTemplateDemo3 {<br> public static void main(String[] args) {<br> &#x2F;&#x2F;1. 获取容器<br> ApplicationContext ac &#x3D; new ClassPathXmlApplicationContext(“bean.xml”);<br> &#x2F;&#x2F;2. 获取对象<br> JdbcTemplate jt &#x3D; ac.getBean(“jdbcTemplate”,JdbcTemplate.class);<br> &#x2F;&#x2F;3. 执行操作<br>&#x2F;&#x2F;		&#x2F;&#x2F;保存<br>&#x2F;&#x2F;		jt.update(“insert into account(name,balance,uid)values(?,?,?)”,”屈心”,10000,32);<br>&#x2F;&#x2F;		&#x2F;&#x2F;更新<br>&#x2F;&#x2F;		jt.update(“update account set name &#x3D; ?,balance &#x3D; ?, uid &#x3D; ? where id &#x3D; ?”,”楚留香”,100000,5,4);<br>&#x2F;&#x2F;		&#x2F;&#x2F;删除<br>&#x2F;&#x2F;		jt.update(“delete from account where id &#x3D; ?”,5);</p>
<pre><code> //查询所有
 //需要一个参数RowMapper(),定义封装策略
</code></pre>
</li>
</ul>
<p>&#x2F;&#x2F;		List<Account> accounts&#x3D;jt.query(“select * from account where balance &gt; ?”,new AccountRowMapper(),5000);<br>        &#x2F;&#x2F;使用spring中提供的实现类<br>        List<Account> accounts&#x3D;jt.query(“select * from account where balance &gt; ?”,new BeanPropertyRowMapper<Account>(Account.class),5000);</p>
<pre><code>    for (Account account : accounts) &#123;
        System.out.println(account);
    &#125;
    //查询一个
    List&lt;Account&gt; acc=jt.query(&quot;select * from account where id = ?&quot;,new BeanPropertyRowMapper&lt;Account&gt;(Account.class),2);
    System.out.println(acc.isEmpty()?&quot;没有内容&quot;:acc.get(0));

    //查询返回一行一列(使用聚合函数,但不增加group by 子句)
    Long count = jt.queryForObject(&quot;select count(*) from account where balance &gt; ? &quot;,Long.class,5000);
    System.out.println(count);
&#125;
</code></pre>
<p>}</p>
<p>&#x2F;**<br> *</p>
<ul>
<li>定义Account的封装策略</li>
<li> <em>&#x2F;<br>class AccountRowMapper implements RowMapper<Account>{<br>  &#x2F;</em>*<ul>
<li>把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中</li>
<li>@param resultSet</li>
<li>@param i</li>
<li>@return</li>
<li>@throws SQLException<br>   *&#x2F;</li>
</ul>
<p>  @Override<br>  public Account mapRow(ResultSet resultSet, int i) throws SQLException {<br>      Account account &#x3D; new Account();<br>      account.setId(resultSet.getInt(“id”));<br>      account.setName(resultSet.getString(“name”));<br>      account.setBalance(resultSet.getDouble(“balance”));<br>      account.setUid(resultSet.getInt(“uid”));<br>      return account;<br>  }</p>
</li>
</ul>
<h2 id="-1"><a href="#-1" class="headerlink" title="}"></a>}</h2><p>DAO实现</p>
<p>package com.sqtian.dao.impl;</p>
<p>import com.sqtian.dao.IAccountDao;<br>import com.sqtian.domain.Account;<br>import org.springframework.jdbc.core.BeanPropertyRowMapper;<br>import org.springframework.jdbc.core.JdbcTemplate;</p>
<p>import java.util.List;</p>
<p>public class AccountDaoImpl implements IAccountDao {<br>    private JdbcTemplate jdbcTemplate;</p>
<pre><code>public void setJdbcTemplate(JdbcTemplate jdbcTemplate) &#123;
    this.jdbcTemplate = jdbcTemplate;
&#125;



@Override
public Account findAccountById(Integer accountId) &#123;
    List&lt;Account&gt; accounts = jdbcTemplate.query(&quot;select * from Account where id = ?&quot;, new BeanPropertyRowMapper&lt;Account&gt;(Account.class), accountId);

    return accounts.isEmpty() ? null:accounts.get(0);
&#125;

@Override
public Account findAccountByName(String accountName) &#123;
    //写法不同,因为名字可能相同
    List&lt;Account&gt; accounts = jdbcTemplate.query(&quot;select * from Account where name = ?&quot;, new BeanPropertyRowMapper&lt;Account&gt;(Account.class), accountName);
    if (accounts.isEmpty())&#123;
        return null;
    &#125;else if(accounts.size()&gt;1)&#123;
        throw new RuntimeException(&quot;结果集不唯一&quot;);
    &#125;else &#123;
        return accounts.get(0);
    &#125;

&#125;

@Override
public void updateAccount(Account account) &#123;
    jdbcTemplate.update(&quot;update account set name=?,balance=?,uid=? where id=?&quot;,account.getName(),account.getBalance(),account.getUid(),account.getId());
&#125;
</code></pre>
<h2 id="-2"><a href="#-2" class="headerlink" title="}"></a>}</h2><p>package com.sqtian.jdbctemplate;</p>
<p>import com.sqtian.dao.IAccountDao;<br>import com.sqtian.domain.Account;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;</p>
<p>&#x2F;**</p>
<ul>
<li>JdbcTemplate的最基本用法<br> *&#x2F;<br>public class JdbcTemplateDemo4 {<br> public static void main(String[] args) {<br> &#x2F;&#x2F;1. 获取容器<br> ApplicationContext ac &#x3D; new ClassPathXmlApplicationContext(“bean.xml”);<br> &#x2F;&#x2F;2. 获取对象<br> IAccountDao accountDao &#x3D; ac.getBean(“accountDao”, IAccountDao.class);<br> &#x2F;&#x2F;3. 执行操作<br> System.out.println(accountDao.findAccountById(7));<br> System.out.println(accountDao.findAccountByName(“西门吹雪”));<br><br> Account account &#x3D; new Account();<br> account.setUid(33);<br> account.setName(“南宫问天”);<br> account.setBalance(50000);<br> account.setId(8);<br> accountDao.updateAccount(account);<br> }</li>
</ul>
<p>}</p>
<hr>
<pre><code>&lt;!--配置账户的持久层--&gt;
&lt;bean id=&quot;accountDao&quot; class=&quot;com.sqtian.dao.impl.AccountDaoImpl&quot;&gt;
    &lt;property name=&quot;jdbcTemplate&quot; ref=&quot;jdbcTemplate&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<hr>
<p>如果有多个DAO实现类,则存在许多重复代码<br>比如:<br>    private JdbcTemplate jdbcTemplate;</p>
<pre><code>public void setJdbcTemplate(JdbcTemplate jdbcTemplate) &#123;
    this.jdbcTemplate = jdbcTemplate;
&#125;
</code></pre>
<p>需要抽取重复代码</p>
<p>public class JdbcDaoSupport {<br>    private JdbcTemplate jdbcTemplate;</p>
<pre><code>public void setJdbcTemplate(JdbcTemplate jdbcTemplate) &#123;
    this.jdbcTemplate = jdbcTemplate;
&#125;

public JdbcTemplate getJdbcTemplate() &#123;
    return jdbcTemplate;
&#125;

public void setDataSource(DataSource dataSource)&#123;
    if(jdbcTemplate == null)&#123;
        jdbcTemplate = createJdbcTemplate(dataSource); //可以不用注入template了直接注入datasource
    &#125;
&#125;

private JdbcTemplate createJdbcTemplate(DataSource dataSource) &#123;
    return new JdbcTemplate(dataSource);
&#125;
</code></pre>
<p>}</p>
<hr>
<p>实际上,spring中提供了JdbcDaosupport类</p>
<p>区别,用自己的类可以加注解自动注入, 用提供的类因为是只读的,不能加注解了</p>
<ol start="2">
<li><p>作业：<br> 利用spring基于AOP的事务控制对account案例改进
 </p>
<ol>
<li>基于xnl的方法</li>
</ol>
<p> 在bean.xml中添加AOP配置</p>
 <!--配置AOP-->
<p> <a href="aop:config">aop:config</a><br>     <!--配置通用的切入点表达式--><br>     &lt;aop:pointcut id&#x3D;”pt1” expression&#x3D;”excution(* com.sqtian.service.impl.*.*(..))”&gt;</aop:pointcut><br>     &lt;aop:aspect id&#x3D;”txAdvice” ref&#x3D;”txManager”&gt;<br>         <!--配置前置通知 开启事务--><br>         &lt;aop:before method&#x3D;”beginTransaction” pointcut-ref&#x3D;”pt1”&gt;</aop:before><br>         <!--配置后置通知 提交事务--><br>         &lt;aop:after-returning method&#x3D;”afterReturningTransaction” pointcut-ref&#x3D;”pt1”&gt;</aop:after-returning></p>
<pre><code>     &lt;!--配置异常通知 回滚事务--&gt;
     &lt;aop:after-throwing method=&quot;afterThrowingTransaction&quot; pointcut-ref=&quot;pt1&quot;&gt;&lt;/aop:after-throwing&gt;

     &lt;!--配置最终通知 释放连接--&gt;
     &lt;aop:after method=&quot;release&quot; pointcut-ref=&quot;pt1&quot;&gt;&lt;/aop:after&gt;
 &lt;/aop:aspect&gt;
</code></pre>
<p> </aop:config></p>
<ol start="2">
<li>基于注解的方法<ol>
<li>给Service加上注解,删除不必要的set方法,删除bean.xml中对应配置</li>
</ol>
</li>
</ol>
</li>
</ol>
<p>@Service(“accountService”)<br>public class AccountServiceImpl implements IAccountService {</p>
<pre><code>//自动注入就不需要set方法了
@Autowired
private IAccountDao accountDao;
</code></pre>
<h2 id="……"><a href="#……" class="headerlink" title="……
        "></a>……
        </h2><pre><code>    2. 给Dao加上注解,并删除多余配置
</code></pre>
<p>@Repository(“accountDao”)<br>public class AccountDaoImpl implements IAccountDao {</p>
<pre><code>@Autowired
private QueryRunner runner;

//不再希望通过queryRunner里取连接,而是通过connectionUtils取
//删去原来的注入&lt;constructor-arg name=&quot;ds&quot; ref=&quot;dataSource&quot;&gt;&lt;/constructor-arg&gt;
//自己写的类加上注解后可以在bean中删掉配置
@Autowired
private ConnectionUtils connectionUtils;
</code></pre>
<hr>
<pre><code>    3. 连接工具类
</code></pre>
<p>@Component(“connectionUtils”)<br>public class ConnectionUtils {<br>    private ThreadLocal<Connection> tl &#x3D; new ThreadLocal<Connection>();</p>
<pre><code>@Autowired
private DataSource dataSource;
</code></pre>
<h2 id="…"><a href="#…" class="headerlink" title="…."></a>….</h2><pre><code>    4. 事务管理器
</code></pre>
<p>**</p>
<ul>
<li><p>和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接<br> *&#x2F;<br>@Component(“txManager”)<br>&#x2F;&#x2F;切面注解<br>@Aspect<br>public class TransactionManager {</p>
<p> @Autowired<br> private ConnectionUtils connectionUtils;</p>
<p> &#x2F;&#x2F;配置切入点<br> @Pointcut(“excution(* com.sqtian.service.impl.<em>.</em>(..))”)<br> private void pt1(){}</p>
<p> &#x2F;**</p>
<ul>
<li>开启事务<br>  *&#x2F;<br> @Before(“pt1()”)<br> public void beginTransaction(){<br> try {<br> connectionUtils.getThreadConnection().setAutoCommit(false);<br> } catch (SQLException e) {<br> e.printStackTrace();<br> }<br> }</li>
</ul>
<p> &#x2F;**</p>
<ul>
<li>提交事务<br>  *&#x2F;<br> @AfterReturning(“pt1()”)<br> public void commit(){<br> try {<br> connectionUtils.getThreadConnection().commit();<br> } catch (SQLException e) {<br> e.printStackTrace();<br> }<br> }</li>
</ul>
<p> &#x2F;**</p>
<ul>
<li>回滚事务<br>  *&#x2F;<br> @AfterThrowing(“pt1()”)<br> public void rollback(){<br> try {<br> connectionUtils.getThreadConnection().rollback();<br> } catch (SQLException e) {<br> e.printStackTrace();<br> }<br> }</li>
</ul>
<p> &#x2F;**</p>
<ul>
<li>释放连接<br>  *&#x2F;<br> @After(“pt1()”)<br> public void release(){<br> try {<br> connectionUtils.getThreadConnection().close();&#x2F;&#x2F;换回连接池中<br> connectionUtils.removeConnection();<br> } catch (SQLException e) {<br> e.printStackTrace();<br> }<br> }</li>
</ul>
</li>
</ul>
<p>}</p>
<hr>
<p>然而,aop注解的四种通知运行顺序是存在问题的,以上代码并不能满足需求<br>需要通过环绕通知来实现</p>
<pre><code>/**
 * 通过环绕通知注解控制事务
 * @param pjp
 * @return
 */
@Around(&quot;pt1&quot;)
public Object aroundAdvice(ProceedingJoinPoint pjp)&#123;
    Object retuenValue = null;

    try&#123;
        //1. 获取参数
        Object[] args = pjp.getArgs();
        //2. 开启事务
        this.beginTransaction();
        //3. 执行方法
        retuenValue = pjp.proceed();
        //4. 提交事务
        this.commit();

        //返回结果
        return retuenValue;
    &#125;catch (Throwable t)&#123;
        //5. 回滚事务
        this.rollback();
        throw new RuntimeException(t);
    &#125;finally &#123;
        //6. 释放资源
        this.release();
    &#125;
&#125;	
</code></pre>
<ol start="3">
<li>spring中的事务控制<br> 基于xml<br> 基于注解</li>
</ol>
<hr>
<p>进入 mysql -u -p;</p>
<p>show databases;  </p>
<p>show tables; 显示所有表</p>
<p>use 库名； 操作数据库</p>
<p>打开服务 cmd services.msc</p>
<p>事件查看器 eventvwr</p>
<p>创建库 create database mydb;</p>
<p>导入数据 use mydb;</p>
<pre><code>     source d:/wc.sql;
</code></pre>
<p>修改数据库root密码</p>
<p>mysql -u root</p>
<p>　　mysql&gt; use mysql;</p>
<p>　　mysql&gt; UPDATE user SET Password &#x3D; PASSWORD(‘newpass’) WHERE user &#x3D; ‘root’;</p>
<p>　　mysql&gt; FLUSH PRIVILEGES;</p>
<p>在丢失root密码的时候，可以这样</p>
<p>　　mysqld_safe –skip-grant-tables&amp;</p>
<p>　　mysql -u root mysql</p>
<p>　　mysql&gt; UPDATE user SET password&#x3D;PASSWORD(“new password”) WHERE user&#x3D;’root’;</p>
<p>　　mysql&gt; FLUSH PRIVILEGES;</p>
<hr>
<h2 id="spring基于xml的声明式事务控制"><a href="#spring基于xml的声明式事务控制" class="headerlink" title="spring基于xml的声明式事务控制"></a>spring基于xml的声明式事务控制</h2><ol>
<li><p>导入依赖坐标</p>
<?xml version="1.0" encoding="UTF-8"?>
<p><project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><br> <modelVersion>4.0.0</modelVersion></p>
<p> <groupId>org.example</groupId><br> <artifactId>comsqtian.springDay04.tx</artifactId><br> <version>1.0-SNAPSHOT</version></p>
 <build>
     <plugins>
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <configuration>
                 <source>6</source>
                 <target>6</target>
             </configuration>
         </plugin>
     </plugins>
 </build>
 <packaging>jar</packaging>

 <dependencies>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>5.0.2.RELEASE</version>
     </dependency>

<pre><code> &lt;dependency&gt;
     &lt;groupId&gt;org.springframework&lt;/groupId&gt;
     &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
     &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
 &lt;/dependency&gt;

 &lt;dependency&gt;
     &lt;groupId&gt;org.springframework&lt;/groupId&gt;
     &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
     &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
 &lt;/dependency&gt;

 &lt;dependency&gt;
     &lt;groupId&gt;mysql&lt;/groupId&gt;
     &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
     &lt;version&gt;5.1.6&lt;/version&gt;
 &lt;/dependency&gt;

 &lt;dependency&gt;
     &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
     &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
     &lt;version&gt;1.8.7&lt;/version&gt;
 &lt;/dependency&gt;

 &lt;dependency&gt;
     &lt;groupId&gt;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;4.13&lt;/version&gt;
 &lt;/dependency&gt;

 &lt;dependency&gt;
     &lt;groupId&gt;org.springframework&lt;/groupId&gt;
     &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
     &lt;version&gt;5.0.2.RELEASE&lt;/version&gt;
 &lt;/dependency&gt;
</code></pre>
 </dependencies></li>
</ol>
</project>

<hr>
<ol start="2">
<li>配置bean.xml</li>
</ol>
<?xml version="1.0" encoding="UTF-8"?>
<p><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"></p>
<pre><code>&lt;!--配置账户的持久层--&gt;
&lt;bean id=&quot;accountDao&quot; class=&quot;com.sqtian.dao.impl.AccountDaoImpl&quot;&gt;
    &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;accountService&quot; class=&quot;com.sqtian.service.impl.AccountServiceImpl&quot;&gt;
    &lt;property name=&quot;accountDao&quot; ref=&quot;accountDao&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;



&lt;bean id=&quot;dataSource&quot; class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
    &lt;!-- collaborators and configuration for this bean go here --&gt;
    &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/lovelycc?characterEncoding=utf8&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;username&quot; value=&quot;root&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;password&quot; value=&quot;root&quot;&gt;&lt;/property&gt;

&lt;/bean&gt;

&lt;!-- spring基于xml的声明式事务控制
    1. 配置事务管理器
    2. 配置事务的通知
        导入约束 tx的名称空间和约束,同时也需要aop的约束
        使用tx:advice标签配置事务通知
            属性:
                id: 给事务通知起一个唯一标识
                transaction-manager: 给事务通知提供一个事务管理器引用
    3. 配置AOP中的通用切入点表达式
    4. 建立事务通知的切入点表达式的对应关系
    5. 配置事务的属性
            是在事务的通知tx:advice标签的内部
--&gt;

&lt;!--配置事务管理器--&gt;
&lt;bean id=&quot;transactionManager&quot; class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
    &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;

&lt;!--配置事务的通知--&gt;
&lt;tx:advice id=&quot;txAdvice&quot; transaction-manager=&quot;transactionManager&quot;&gt;
    &lt;!--配置事务的属性
        isolation: 用于指定事务的隔离级别.DEFAULT使用数据库默认级别
        propagation: 用于指定事务的传播行为,默认是REQUIRED,表示一定会有事务,增删改的选择.查询可以选择SUPPORTS
        read-only: 用于指定事务是否只读.只有查询方法才能设置为true.
        timeout: 用于指定事务的超时时间,默认值-1,表示永不超时
        rollback-for: 用于指定一个异常,当产生该异常时事务回滚.产生其他异常时事务不回滚.没有值表示任何异常都回滚
        no-rollback-for: 用于指定一个异常,当产生该异常时事务不回滚.产生其他异常时事务回滚.没有值表示任何异常都不回滚

    --&gt;
    &lt;tx:attributes&gt;
        &lt;tx:method name=&quot;*&quot; propagation=&quot;REQUIRED&quot; read-only=&quot;false&quot;/&gt;
        &lt;tx:method name=&quot;find*&quot; propagation=&quot;SUPPORTS&quot; read-only=&quot;true&quot;/&gt;
    &lt;/tx:attributes&gt;

&lt;/tx:advice&gt;

&lt;!--配置AOP--&gt;
&lt;aop:config&gt;
    &lt;!--配置切入点表达式--&gt;
    &lt;aop:pointcut id=&quot;pt1&quot; expression=&quot;execution(* com.sqtian.service.impl.*.*(..))&quot;/&gt;

    &lt;aop:advisor pointcut-ref=&quot;pt1&quot; advice-ref=&quot;txAdvice&quot;/&gt;

&lt;/aop:config&gt;
</code></pre>
</beans>

<hr>
<h2 id="基于注解的声明式事务控制"><a href="#基于注解的声明式事务控制" class="headerlink" title="基于注解的声明式事务控制"></a>基于注解的声明式事务控制</h2><pre><code>1. 配置事务管理器
2. 开启spring对注解事务的支持
    &lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot;/&gt;
3. 在需要事务支持的地方使用@Transactional注解
    @service(&quot;accountService&quot;)
    @Transactional
</code></pre>
<h2 id="基于纯注解的声明式事务控制"><a href="#基于纯注解的声明式事务控制" class="headerlink" title="基于纯注解的声明式事务控制"></a>基于纯注解的声明式事务控制</h2><ol>
<li>ServiceImpl</li>
</ol>
<p>&#x2F;**</p>
<ul>
<li><p>账户的业务层实现类</p>
</li>
<li></li>
<li><p>事务控制应该都是在业务层<br> *&#x2F;<br>@Service(“accountService”)<br>&#x2F;&#x2F;支持事务的注解<br>@Transactional(propagation &#x3D; Propagation.SUPPORTS,readOnly &#x3D; true)<br>public class AccountServiceImpl implements IAccountService {</p>
<p> @Autowired<br> private IAccountDao accountDao;</p>
<p> public Account findAccountById(Integer accountId) {<br> return accountDao.findAccountById(accountId);<br> }</p>
<p> @Transactional(propagation &#x3D; Propagation.REQUIRED,readOnly &#x3D; false)<br> public void transfer(String sourceName, String targetName, Double money) {<br> &#x2F;&#x2F;2.1. 根据名称查询转出账户<br> Account source &#x3D; accountDao.findAccountByName(sourceName);<br> &#x2F;&#x2F;2.2. 根据名称查询转入账户<br> Account target &#x3D; accountDao.findAccountByName(targetName);<br> &#x2F;&#x2F;2.3. 转出账户减钱<br> source.setBalance(source.getBalance()-money);<br> &#x2F;&#x2F;2.4. 转入账户加钱<br> target.setBalance(target.getBalance()+money);<br> &#x2F;&#x2F;2.5. 更新转出账户<br> accountDao.updateAccount(source);<br> &#x2F;&#x2F;2.6. 更新转入账户<br> accountDao.updateAccount(target);<br><br> System.out.println(“转账成功”);<br> }</p>
</li>
</ul>
<h2 id="-3"><a href="#-3" class="headerlink" title="}"></a>}</h2><ol start="2">
<li><p>DAOIImpl<br>@Repository(“accountDao”)<br>public class AccountDaoImpl implements IAccountDao {</p>
<p> @Autowired<br> private JdbcTemplate jdbcTemplate;</p>
<p> @Override<br> public Account findAccountById(Integer accountId) {<br> List<Account> accounts &#x3D; jdbcTemplate.query(“select * from Account where id &#x3D; ?”, new BeanPropertyRowMapper<Account>(Account.class), accountId);<br><br> return accounts.isEmpty() ? null:accounts.get(0);<br> }</p>
<p> @Override<br> public Account findAccountByName(String accountName) {<br> &#x2F;&#x2F;写法不同,因为名字可能相同<br> List<Account> accounts &#x3D; jdbcTemplate.query(“select * from Account where name &#x3D; ?”, new BeanPropertyRowMapper<Account>(Account.class), accountName);<br> if (accounts.isEmpty()){<br>     return null;<br> }else if(accounts.size()&gt;1){<br>     throw new RuntimeException(“结果集不唯一”);<br> }else {<br>     return accounts.get(0);<br> }<br> }</p>
<p> @Override<br> public void updateAccount(Account account) {<br> jdbcTemplate.update(“update account set name&#x3D;?,balance&#x3D;?,uid&#x3D;? where id&#x3D;?”,account.getName(),account.getBalance(),account.getUid(),account.getId());<br> }</p>
</li>
</ol>
<h2 id="-4"><a href="#-4" class="headerlink" title="}"></a>}</h2><ol start="3">
<li>配置类</li>
</ol>
<h2 id="x2F-Spring的配置类-相当于bean-xml-x2F-Configuration-ComponentScan-“com-sqtian”-Import-JdbcConfig-class-TransactionConfig-class-PropertySource-“jdbcConfig-properties”-x2F-x2F-开启事务注解的支持-EnableTransactionManagementpublic-class-SpringConfiguration"><a href="#x2F-Spring的配置类-相当于bean-xml-x2F-Configuration-ComponentScan-“com-sqtian”-Import-JdbcConfig-class-TransactionConfig-class-PropertySource-“jdbcConfig-properties”-x2F-x2F-开启事务注解的支持-EnableTransactionManagementpublic-class-SpringConfiguration" class="headerlink" title="&#x2F;** * Spring的配置类,相当于bean.xml *&#x2F;@Configuration@ComponentScan(“com.sqtian”)@Import({JdbcConfig.class,TransactionConfig.class})@PropertySource(“jdbcConfig.properties”)&#x2F;&#x2F;开启事务注解的支持@EnableTransactionManagementpublic class SpringConfiguration {}"></a>&#x2F;**<br> * Spring的配置类,相当于bean.xml<br> *&#x2F;<br>@Configuration<br>@ComponentScan(“com.sqtian”)<br>@Import({JdbcConfig.class,TransactionConfig.class})<br>@PropertySource(“jdbcConfig.properties”)<br>&#x2F;&#x2F;开启事务注解的支持<br>@EnableTransactionManagement<br>public class SpringConfiguration {<br>}</h2><p>&#x2F;**</p>
<ul>
<li>和连接数据库相关的配置类<br> *&#x2F;</li>
</ul>
<p>public class JdbcConfig {</p>
<pre><code>@Value(&quot;$&#123;jdbc.driver&#125;&quot;)
private String driver;

@Value(&quot;$&#123;jdbc.url&#125;&quot;)
private String url;

@Value(&quot;$&#123;jdbc.username&#125;&quot;)
private String username;

@Value(&quot;$&#123;jdbc.password&#125;&quot;)
private String password;



/**
 * 创建jdbcTemplate
 * @param dataSource
 * @return
 */
@Bean(name=&quot;jdbcTemplate&quot;)
public JdbcTemplate createJdbcTemplate(DataSource dataSource)&#123;
    return new JdbcTemplate(dataSource);
&#125;

@Bean(&quot;dataSource&quot;)
public DataSource createDataSource()&#123;
    DriverManagerDataSource ds = new DriverManagerDataSource();

    ds.setDriverClassName(driver);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
&#125;
</code></pre>
<p>}</p>
<hr>
<p>jdbc.driver&#x3D;com.mysql.jdbc.Driver<br>jdbc.url&#x3D;jdbc:mysql:&#x2F;&#x2F;localhost:3306&#x2F;lovelycc?characterEncoding&#x3D;utf8<br>jdbc.username&#x3D;root<br>jdbc.password&#x3D;root</p>
<hr>
<p>&#x2F;**</p>
<ul>
<li>和事务相关的配置类<br> *&#x2F;</li>
</ul>
<p>public class TransactionConfig {</p>
<pre><code>/**
 * 用于创建事务管理器对象
 * @param dataSource
 * @return
 */
@Bean(&quot;transactionManager&quot;)
public PlatformTransactionManager createTransactionManager(DataSource dataSource)&#123;
    return new DataSourceTransactionManager(dataSource);
&#125;
</code></pre>
<p>}</p>
<hr>
<ol start="4">
<li>测试类</li>
</ol>
<p>@RunWith(SpringJUnit4ClassRunner.class)</p>
<p>@ContextConfiguration(classes &#x3D; SpringConfiguration.class)<br>public class AccountServiceTest {</p>
<pre><code>@Autowired
private IAccountService accountService;
@Test
public void testTransfer() &#123;
    accountService.transfer(&quot;楚留香&quot;,&quot;西门吹雪&quot;,5000d);
&#125;
</code></pre>
<p>}</p>
<hr>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/shiqing/about" rel="external nofollow noreferrer">ShiQing</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shiqing.gitee.io/shiqing/2020/06/29/java-kuang-jia/javanote-spring-day04/">https://shiqing.gitee.io/shiqing/2020/06/29/java-kuang-jia/javanote-spring-day04/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/shiqing/about" target="_blank">ShiQing</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/shiqing/tags/Java%E6%A1%86%E6%9E%B6/">
                                    <span class="chip bg-color">Java框架</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/shiqing/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/shiqing/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/shiqing/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/shiqing/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/shiqing/2020/07/08/java-kuang-jia/javanote-springmvc-day01/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/0.jpg" class="responsive-img" alt="&#39;JavaNote_SpringMVC_Day01&#39;">
                        
                        <span class="card-title">&#39;JavaNote_SpringMVC_Day01&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            day1第一章：SpringMVC的基本概念开发架构一般基于两种形式：C&#x2F;S架构和B&#x2F;S架构。JavaEE开发中几乎全都是基于B&#x2F;S架构的开发。B&#x2F;S架构中，标准的三层架构包括：表现层、业务层、持久层
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-07-08
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E6%A1%86%E6%9E%B6/">
                        <span class="chip bg-color">Java框架</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/shiqing/2020/06/29/java-kuang-jia/javanote-spring-day03/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/16.jpg" class="responsive-img" alt="JavaNote_Spring_Day03">
                        
                        <span class="card-title">JavaNote_Spring_Day03</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Day3spring中的app和基于XML以及注解的AOP配置

完善我们的account案例

分析案例中的问题

回顾之前讲过的一个技术: 动态代理

动态代理另一种实现方式

解决案例中的问题

AOP的概念

spring中的AOP
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-06-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E6%A1%86%E6%9E%B6/">
                        <span class="chip bg-color">Java框架</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/shiqing/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/shiqing/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




        <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/shiqing/about" target="_blank">ShiQing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2528393970@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2528393970" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2528393970" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/shiqing/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/shiqing/search.xml', 'searchInput', 'searchResult');
});
</script>

        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


        <script src="/shiqing/libs/materialize/materialize.min.js"></script>
        <script src="/shiqing/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/shiqing/libs/aos/aos.js"></script>
        <script src="/shiqing/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/shiqing/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/shiqing/js/matery.js"></script>

        <!-- Baidu Analytics -->

        <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

        
        <script src="/shiqing/libs/others/clicklove.js" async="async"></script>
        
        
        <script async src="/shiqing/libs/others/busuanzi.pure.mini.js"></script>
        

        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我~看不见我~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 背景樱花飘落特效 -->
        
            <script type="text/javascript">
                //只在桌面版网页启用特效
                var windowWidth = $(window).width();
                if (windowWidth > 768) {
                    document.write('<script type="text/javascript" src="/js/xuehuapiaoluo.js"><\/script>');
                }
            </script>
        

        

        


        
        

        

        

        
        <script src="/shiqing/libs/instantpage/instantpage.js" type="module"></script>
        

    </body>

</html>
